package com.zzyl.framework.config;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.SdkException;
import com.huaweicloud.sdk.core.region.Region;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class IotClientConfig {
    
    private static final Logger logger = LoggerFactory.getLogger(IotClientConfig.class);

    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;

    @Bean
    public IoTDAClient huaWeiIotInstance() {
        try {
            // 检查必要配置是否存在
            if (huaWeiIotConfigProperties.getAk() == null || 
                huaWeiIotConfigProperties.getSk() == null ||
                huaWeiIotConfigProperties.getProjectId() == null ||
                huaWeiIotConfigProperties.getRegionId() == null ||
                huaWeiIotConfigProperties.getEndpoint() == null) {
                logger.warn("华为云IoT配置不完整，跳过IoT客户端初始化");
                return null;
            }
            
            ICredential auth = new BasicCredentials()
                    .withAk(huaWeiIotConfigProperties.getAk())
                    .withSk(huaWeiIotConfigProperties.getSk())
                    // 标准版/企业版需要使用衍生算法，基础版请删除配置"withDerivedPredicate"
                    .withDerivedPredicate(BasicCredentials.DEFAULT_DERIVED_PREDICATE)
                    .withProjectId(huaWeiIotConfigProperties.getProjectId());

            return IoTDAClient.newBuilder()
                    .withCredential(auth)
                    // 标准版/企业版：需自行创建Region对象，基础版：请使用IoTDARegion的region对象，如"withRegion(IoTDARegion.CN_NORTH_4)"
                    .withRegion(new Region(huaWeiIotConfigProperties.getRegionId(), huaWeiIotConfigProperties.getEndpoint()))
                    // .withRegion(IoTDARegion.CN_NORTH_4)
                    .build();
        } catch (Exception e) {
            logger.error("初始化华为云IoT客户端失败: {}", e.getMessage(), e);
            return null;
        }
    }
}